package com.rd.config.security;

import cn.hutool.json.JSONUtil;
import com.rd.common.CommonResult;
import com.rd.mapper.SysRoleMapper;
import com.rd.mapper.SysUserMapper;
import com.rd.pojo.SysMenu;
import com.rd.pojo.SysRole;
import com.rd.pojo.SysUser;
import com.rd.service.SysMenuService;
import com.rd.service.SysUserService;
import com.rd.util.JwtUtil;
import com.rd.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 登录成功处理器
 * 实现AuthenticationSuccessHandler接口，并重写onAnthenticationSuccesss()方法.
 */
@Component
@Slf4j
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysMenuService sysMenuService;
    @Resource
    private SysRoleMapper sysRoleMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        // Authentication authentication 当前用户
        // 前后端项目需要把生成token值传递给vue项目
        response.setContentType("application/json;charset=utf-8");
        //后期会修改成前端传递过来的用户名
        log.info("当前登录的用户是: " + authentication.getName());
        String username = authentication.getName();
        //更新当前登录的时间
        sysUserService.updateLastLoginTime(username);
        SysUser sysUser = sysUserService.getUserByName(username);
        sysUser.setRoles(
                sysRoleMapper.selectRoleByUserId(sysUser.getId())
                        .stream().map(SysRole::getName).
                        collect(Collectors.joining(",")));
        //获取这个用户的权限
        List<SysMenu> menuList = sysMenuService.selectMenuByUserId(sysUser.getId());
        //调用buildTreeMenu方法
        List<SysMenu> treeMenu = sysMenuService.buildTreeMenu(menuList);
        //使用工具生成token
        String token = JwtUtil.genJwtToken(username);
        //创建一个HashMap传递多个值
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("treeMenu", treeMenu);
        /*把当前登录的用户信息,传递给前端vue*/
        map.put("currentUser", sysUser);
        //使用流
        CommonResult commonResult =
                ResultUtil.buildSuccess("登录成功", map);
        response.getWriter().write(JSONUtil.toJsonStr(commonResult));
    }
}
